package cn.web.lxxf.servlet;

import cn.web.lxxf.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet( urlPatterns = "/lxxfLogin")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("u");
        String password = req.getParameter("p");
        String yzm = req.getParameter("c");

        HttpSession session = req.getSession();
        Object ccc = session.getAttribute("CCC");
        boolean isTrue = yzm != null && yzm.equals(ccc);

        if(!isTrue){
            PrintWriter writer = resp.getWriter();
            writer.write("code is error");
            writer.flush();
            writer.close();
            return;
        }

        String sql = "SELECT id FROM `jk_user` WHERE username = ? AND `password` = MD5(?)";
        Integer id = JdbcUtils.select(sql,Integer.class,username,password);
        if(id!=null && id>0){
            session.setAttribute("UID",id);
            //重定向到首页
            resp.sendRedirect("/lxxf/index.jsp");
        }
        else{
            //重定向到登录页
            resp.sendRedirect("/lxxf/login.jsp");
        }
    }
}
